<template>
  <el-dialog
    :title="form.id?'编辑作品':'新建作品'"
    :visible.sync="visible"
    width="50%"
    :before-close="handleClose"
  >
    <div class="xjzpBox">
    <el-form  :model="form" :rules="rules" ref="formRef" label-width="100px" >
      <!-- 阅读对象 -->
      <el-form-item label="阅读对象" prop="gender" >
        <el-select v-model="form.gender" placeholder="请选择阅读对象" @change="changeSubjectTab">
          <el-option label="男性读者" :value="1"></el-option>
          <el-option label="女性读者" :value="2"></el-option>
        </el-select>
      </el-form-item>

      <!-- 阅读年龄 -->
      <el-form-item label="阅读年龄" prop="age_range">
        <el-select v-model="form.age_range" placeholder="请选择年龄">
          <el-option label="12~18岁" :value="1"></el-option>
          <el-option label="19~25岁" :value="2"></el-option>
          <el-option label="26~35岁" :value="3"></el-option>
          <el-option label="36岁及以上" :value="4"></el-option>
        </el-select>
      </el-form-item>

      <!-- 写作字数 -->
      <el-form-item label="写作字数" prop="words_range">
        <el-select v-model="form.words_range" placeholder="请选择写作字数">
          <el-option label="1~10万字" :value="1"></el-option>
          <el-option label="10~30万字" :value="2"></el-option>
          <el-option label="30~100万字" :value="3"></el-option>
          <el-option label="100~200万字" :value="4"></el-option>
          <el-option label="200~300万字" :value="5"></el-option>
          <el-option label="300~500万字" :value="6"></el-option>
        </el-select>
      </el-form-item>

      <!-- 选择题材 -->
      <el-form-item label="选择题材" prop="subject" class="subject-form-item" >
        <div class="subject-input-row">
          <el-input
            v-model="form.subject"
            placeholder="请选择写作题材"
            @focus="showSubjectPanel = true"
            @click.native="showSubjectPanel = true"
            readonly
            class="subject-input"
          ></el-input>
          <el-button type="primary" plain size="mini" class="ai-suggestion-btn" @click="goAi('topic')">AI建议</el-button>
        </div>
        <transition name="fade">
          <div
            class="subject-panel"
            v-if="showSubjectPanel"
            @mousedown.prevent
          >
            <div class="subject-categories">
              <div
                class="subject-category"
                v-for="category in subjectData[currentSubjectTab]"
                :key="category.name"
              >
                <div class="category-name">{{ category.name }}</div>
                <div class="category-items">
                  <span
                    class="subject-item"
                    v-for="item in category.items"
                    :key="item"
                    @click="selectSubject(item)"
                  >
                    {{ item.name }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </transition>
      </el-form-item>

      <!-- 选择标签 -->
      <el-form-item label="选择标签" prop="tags" class="tag-form-item">
        <div class="tag-input-row">
          <el-input
            v-model="form.tags"
            placeholder="请选择标签"
            class="tag-input"
            @focus="showTagPanel = true"
            @click.native="showTagPanel = true"
            readonly
          ></el-input>

        </div>
        <transition name="fade">
          <div
            class="tag-panel"
            v-if="showTagPanel"
            @mousedown.prevent
          >
            <div
              class="tag-category"
              v-for="categoryObj in tagCategories"
              :key="categoryObj.name"
            >
              <div class="category-label">{{ categoryObj.name }}</div>
              <div class="category-tags">
                <el-tag
                  v-for="tag in categoryObj.tags"
                  :key="tag"
                  :type="selectedTags.includes(tag) ? 'primary' : 'info'"
                  class="tag-item"
                  @click="toggleTag(tag)"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </transition>
      </el-form-item>

      <!-- 故事梗概 -->
      <el-form-item label="故事梗概" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入故事梗概"
          rows="3"
        ></el-input>
        <el-button class="ai-suggestion-btn" type="primary" plain size="mini" @click="goAi('syn')">AI建议</el-button>
      </el-form-item>

      <!-- 作品名称 -->
      <el-form-item label="作品名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入作品名称"></el-input>
        <el-button type="primary" plain size="mini" class="ai-suggestion-btn" @click="goAi('title')">AI建议</el-button>
      </el-form-item>

      <!-- 作品封面 -->
      <el-form-item label="作品封面" prop="cover">
        <ImageUpload2 ref="imageUploadBig" v-model="form.cover" :min-height="192" :limit="1" :isShowTip="false"/>
        <div class="upload-tips">上传的图片尺寸建议大于200*264</div>
      </el-form-item>
    </el-form>
    </div>
    <div class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </div>

  </el-dialog>
</template>

<script>
import {getClassify, createCreation, getTag, saveCreation} from "@/api/work";
import {conversationCreate} from "@/api/conversation";
import {conversationDefault} from "@/api/conversations";

export default {
  props: {
    visible: Boolean,
  },
  data() {
    return {
      form: {
        gender:'',
        target_audience: '',
        age_range: '',
        words_range: '',
        subject: '',
        tags: '',
        description: '',
        title: '',
        cover: '',
        classify_id: null
      },
      rules: {
        gender:[{ required: true, message: '请选择阅读对象', trigger: 'change' }],
        age_range:[{ required: true, message: '请选择阅读年龄', trigger: 'change' }],
        words_range:[{ required: true, message: '请选择写作字数', trigger: 'change' }],
        title: [{ required: true, message: '请输入作品名称', trigger: 'blur' }],
        subject: [{ required: true, message: '请选择题材', trigger: 'change' }],
        tags: [{ required: true, message: '请选择标签', trigger: 'change' }],
        description:[{ required: true, message: '请输入故事梗概', trigger: 'blur' }],

      },
      showSubjectPanel: false,
      showTagPanel: false,
      currentSubjectTab: '男频',
      genderMap: {
        '男频': 1,
        '女频': 2
      },
      subjectData: {
        '男频': [],
        '女频': []
      },
      selectedVendor:"",
      tagCategories: [], // 初始化为空数组
      selectedTags: [],   // 初始化为空数组
      classifyData: null  // 存储 getClassify 接口返回的完整数据
    };
  },
  mounted() {
    // 默认加载男频数据
    this.getTag(); // 调用 getTag 获取标签数据
    this.getDefaultModel()
    document.addEventListener('click', this.handleDocumentClick);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleDocumentClick);
  },
  methods: {
     //获取默认模型
    async getDefaultModel(){
      const response = await conversationDefault();
      this.selectedVendor=response.model_name
    },
    async goTool(toolId,params){
      this.loading = true;
      try {
        const response = await conversationCreate({
          pattern: 3,
          model:this.selectedVendor,
          ai_tool_id: toolId,
          params:params
        });
        this.modelShow=false;
        this.drawer=false;
        this.$emit("changeDldh", {type:'openNew',id:response.conversation_id,show_prompt:response.show_prompt});
      } catch (error) {
        this.$message.error("创建新对话失败");
      }
    },
    goAi(type){
      //topic、syn、title
      if(type=='topic'){
        var isPass = 0;
        // 检验remark字段
        this.$refs.formRef.validateField(['gender','age_range','words_range'],valid=>{
          if(valid) {
            isPass = 1
            console.log(123)
          }
        });
        if(isPass==0) {
          console.log("校验通过")
          this.goTool(type,{
            Gender:Number(this.form.gender),AgeRange:Number(this.form.age_range),WordsRange:Number(this.form.words_range)
          })
        }

      }
      if(type=='syn'){
        var isPass = 0;
        // 检验remark字段
        this.$refs.formRef.validateField(['gender','age_range','words_range','subject'],valid=>{
          if(valid) {
            isPass = 1
            console.log(123)
          }
        });
        if(isPass==0) {
          console.log("校验通过")
          this.goTool(type,{
            Gender:Number(this.form.gender),AgeRange:Number(this.form.age_range),WordsRange:Number(this.form.words_range),classifyID:Number(this.form.classify_id),tag:this.form.tags
          })
        }
      }
      if(type=='title'){
        var isPass = 0;
        // 检验remark字段
        this.$refs.formRef.validateField(['gender','age_range','words_range','subject','tags','description'],valid=>{
          if(valid) {
            isPass = 1
            console.log(123)
          }
        });
        if(isPass==0) {
          console.log("校验通过")
          this.goTool(type,{
            Gender:Number(this.form.gender),AgeRange:Number(this.form.age_range),WordsRange:Number(this.form.words_range),classifyID:Number(this.form.classify_id),tag:this.form.tags,summary:this.form.description
          })
        }
      }
    },
    init(detailInfo){
      this.form=detailInfo
      this.form.cover='http://116.205.104.204:8080/api/v1/creations/'+detailInfo.cover_image
      if(this.form.classify&&this.form.classify.Sub){
        this.form.subject=this.form.classify.Sub
      }
      if(this.form.gender==1){
        this.loadClassifyData('男频');
      }else{
        this.loadClassifyData('女频');
      }
    },
    changeSubjectTab(){
      if(this.form.gender==1){
        this.loadClassifyData('男频');

      }else{
        this.loadClassifyData('女频');
      }
      this.form.subject=''
    },
    getTag() {
      getTag({ 'key': 'jqsj' }).then(res => {
        const data = res;
        const categories = [];

        for (const [categoryName, tags] of Object.entries(data)) {
          const tagNames = tags.map(tag => tag.name);
          categories.push({
            name: categoryName,
            tags: tagNames
          });
        }
        this.tagCategories = categories;
      }).catch(error => {
        console.error('获取标签数据失败:', error);
        this.$message.error('获取标签数据失败，请稍后重试');
      });
    },
    loadClassifyData(tab) {
      const gender = this.genderMap[tab];
      this.currentSubjectTab=tab
      getClassify({ gender }).then(res => {
        this.classifyData = res;

        // 根据返回的 categories 数据构造 subjectData
        this.subjectData[tab] = res.categories.map(category => {
          return {
            name: category.name,
            items: category.sub_categories
          };
        });
      }).catch(error => {
        console.error('获取题材数据失败:', error);
        this.$message.error('获取题材数据失败，请稍后重试');
      });
    },
    switchSubjectTab(tab) {
      this.currentSubjectTab = tab;
      this.loadClassifyData(tab);
    },
    handleClose() {
      this.$emit('update:visible', false);
    },
    handleSubmit() {
      console.log(this.form)
      let file = this.$refs.imageUploadBig.getFile();
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // var requestData = {
          //   title: this.form.title,
          //   classify_id: this.form.classify_id || 1,
          //   tags: this.form.tags,
          //   description: this.form.story_summary,
          //   age_range: this.form.age_range,
          //   words_range: this.form.word_count,
          //   cover_image: file
          // };
          // console.log(requestData)
          // return false
          let formData = new FormData();
          formData.append("title", this.form.title);
          formData.append("gender",this.form.gender);
          formData.append("classify_id", this.form.classify_id);
          formData.append("tags", this.form.tags);
          formData.append("description", this.form.description);
          formData.append("age_range", this.form.age_range);
          formData.append("words_range", this.form.words_range);
          if(file){
            formData.append("cover_image", file);
          }
          formData.append("title", this.form.title);
          if(this.form.id){
            formData.append('id', this.form.id);
            saveCreation(formData).then((res) => {
              this.$message.success('作品修改成功');
              this.$emit('submit', true);
              this.handleClose();
            }).catch(() => {
              this.$message.error('创建失败，请稍后重试');
            });
          }else{
            createCreation(formData).then((res) => {
              this.$message.success('作品创建成功');
              this.$emit('submit', true);

              this.handleClose();
            }).catch(() => {
              this.$message.error('创建失败，请稍后重试');
            });
          }

        }
      });
    },
    handleAISuggestion() {
      this.$message.info('AI建议功能暂未实现');
    },
    handleAIWritingGuide() {
      this.$message.success('AI创作引导...');
    },
    handleUploadSuccess(response) {
      this.form.cover = response.path;
      this.$message.success('封面上传成功');
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件');
        return false;
      }
      return true;
    },
    handleDocumentClick(e) {
      const subjectInput = this.$el.querySelector('.subject-form-item');
      const tagInput = this.$el.querySelector('.tag-form-item');
      if (subjectInput && !subjectInput.contains(e.target)) {
        this.showSubjectPanel = false;
      }
      if (tagInput && !tagInput.contains(e.target)) {
        this.showTagPanel = false;
      }
    },
    selectSubject(item) {
      this.form.classify_id=item.id
      this.form.subject = item.name
      this.showSubjectPanel = false;
    },
    toggleTag(tag) {
      const index = this.selectedTags.indexOf(tag);
      if (index >= 0) {
        this.selectedTags=[];
      } else {
        this.selectedTags=[tag];
        this.showTagPanel=false;
      }
      this.form.tags = this.selectedTags.join('，'); // 使用中文逗号分隔
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-select {
  width: 100%;
}


.subject-form-item, .tag-form-item {
  position: relative;
}
.subject-input-row, .tag-input-row {
  display: flex;
  align-items: center;
  position: relative;
}
.subject-input, .tag-input {
  width: 100%;
  cursor: pointer;
}
.ai-suggestion-btn {
  position: absolute;
  right:-80px;
  top:9px;
  background: linear-gradient( 90deg, #3C7DFF 0%, #165DEB 100%);
  border-radius: 6px 6px 6px 6px;
  height: 30px;
  color:#fff;
}

/* 题材选择下拉面板 */
.subject-panel {
  position: absolute;
  top: 68px;
  left: 0;
  width: 100%;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  z-index: 2000;
}
.subject-tabs {
  display: flex;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 10px;
}
.subject-tab {
  margin-right: 20px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  padding: 5px 0;
}
.subject-tab.active {
  font-size: 16px;
  color: #165DEB;
  border-bottom: 3px solid  #165DEB;;
  font-weight: bold;
}
.subject-categories {
  max-height: 200px;
  overflow-y: auto;
}
.subject-category + .subject-category {
  margin-top: 20px;
}
.category-name {
  font-size: 16px;
  color: #00011B;
  line-height: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
.category-items {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.subject-item {
  display: inline-block;
  font-size: 14px;
  color: #00011B;
  line-height: 16px;
  cursor: pointer;
}
.subject-item:hover {
  color:#165DEB;;
}

/* 标签面板下拉 */
.tag-panel {
  position: absolute;
  top: 68px;
  left: 0;
  width: 100%;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  z-index: 2000;
  max-height: 200px;
  overflow-y: auto;
}
.tag-category + .tag-category {
  margin-top: 20px;
}
.category-label {
  font-size: 16px;
  color: #00011B;
  line-height: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;

}
.tag-item {
  cursor: pointer;
}

/* 封面上传展示 */
.upload-container {
  display: inline-block;
  vertical-align: middle;
}
.cover-preview {
  margin-left: 10px;
  color: #67c23a;
  font-size: 12px;
}
.upload-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.fade-enter-active, .fade-leave-active {
  transition: all .2s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.xjzpBox{
   padding: 0 60px;
    padding-right: 100px;
    .el-form-item__label{
      font-size: 14px;
      color: #00011B;
      line-height: 16px;
      margin-bottom: 4px;
      font-weight: normal;
      padding: 0;
    }
    .el-form-item{
      margin-bottom: 24px;
    }
  ::v-deep .el-form-item--medium .el-form-item__label{
    height: 48px;
    line-height: 48px !important;
    font-size: 16px;
    color: rgba(0,1,27,0.5);
  }
  ::v-deep .el-input--medium .el-input__inner {
    height: 48px;
    line-height: 48px !important;
    font-size: 16px;
  }

}
.aiyd{
  background: linear-gradient( 90deg, #3C7DFF 0%, #165DEB 100%);
  color:#fff;
}
</style>
